#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
int gNumber = 0;

void * threadFunction1(void *)
{
    int cnt = 10000000;
    
    while(cnt-- > 0)
    {
        pthread_mutex_lock(&mutex);
        
        ++gNumber;
        
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}

void * threadFunction2(void *)
{
    int cnt = 10000000;
    
    while(cnt-- > 0)
    {
        pthread_mutex_lock(&mutex);
        
        ++gNumber;
        
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}

int main()
{
    pthread_t pthid1 , pthid2;
    
    pthread_mutex_init(&mutex , NULL);

    pthread_create(&pthid1 , NULL , threadFunction1 , NULL);
    pthread_create(&pthid2 , NULL , threadFunction2 , NULL);

    pthread_join(pthid1 , NULL);
    pthread_join(pthid2 , NULL);

    printf("main thread : gNumber = %d \n" , gNumber);

    pthread_mutex_destroy(&mutex);

    printf("\n main thread is over ! \n");

    return 0;
}

